<?php
	/*
		Gatherer Content Managment System
		Copyright © 2007-2009 by Eric Hokanson
		Last changed on $LastChangedDate$
		Revision $Revision: 2 $
		Requires Smarty (www.smarty.net) and the Zend Framework (framework.zend.com)

		This program is free software: you can redistribute it and/or modify
		it under the terms of the GNU General Public License as published by
		the Free Software Foundation, either version 3 of the License, or
		(at your option) any later version.
		
		This program is distributed in the hope that it will be useful,
		but WITHOUT ANY WARRANTY; without even the implied warranty of
		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
		GNU General Public License for more details.
		
		You should have received a copy of the GNU General Public License
		along with this program.  If not, see <http://www.gnu.org/licenses/>.
	*/
	define('MAX_IMAGE_DIM', 320);

	require_once '../../dbconfig.php';
	require_once 'Zend/Session/Namespace.php';
	
	// Session namespace
	$authNamespace = new Zend_Session_Namespace('gcmsadmin');
   	if ($authNamespace->admin != true)
		exit();
		
	$config = $db->fetchRow("SELECT * FROM config");
	$error_code = $_FILES['NewFile']['error'];
	$file_path = '';
	
	// from php.net documentation
	function file_upload_error_message($error_code) {
		switch ($error_code) {
			case UPLOAD_ERR_INI_SIZE:
				return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
			case UPLOAD_ERR_FORM_SIZE:
				return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
			case UPLOAD_ERR_PARTIAL:
				return 'The uploaded file was only partially uploaded';
			case UPLOAD_ERR_NO_FILE:
				return 'No file was uploaded';
			case UPLOAD_ERR_NO_TMP_DIR:
				return 'Missing a temporary folder';
			case UPLOAD_ERR_CANT_WRITE:
				return 'Failed to write file to disk';
			case 9:
				return 'Invalid file extension';
			default:
				return 'Unknown upload error';
		}
	}
	
	if ($error_code === UPLOAD_ERR_OK) { 
	    if ($_GET['Type'] == "Image" && (preg_match("@image/[p]{0,1}jp[e]{0,1}g@i",$_FILES['NewFile']['type']) || preg_match("@image/(.*)png@i",$_FILES['NewFile']['type']) || preg_match("@image/gif@i",$_FILES['NewFile']['type']))) {
			$file_path = rtrim($config['imagedir'], '/') . '/' . $_GET['dir'] . '/' . $_GET['id'] . '/' . $_FILES['NewFile']['name'];
			@mkdir(rtrim($config['imagedir'], '/') . '/' . $_GET['dir'] . '/' . $_GET['id'], 0775, TRUE);
			move_uploaded_file($_FILES['NewFile']['tmp_name'], $file_path) or die('Could not move file.');
			chmod($file_path, 0644);
			// Brute force our way through
			if ((imagetypes() & IMG_JPG) && $orig = @imagecreatefromjpeg($file_path)) { $itype = 'imagejpeg'; }
			else if ((imagetypes() & IMG_PNG) && $orig = @imagecreatefrompng($file_path)) { $itype = 'imagepng'; }
			else if ((imagetypes() & IMG_GIF) && $orig = @imagecreatefromgif($file_path)) { $itype = 'imagegif'; }
			// Get the original image's width and height
			$ow  = imagesx($orig);
			$oh  = imagesy($orig);
			// Build a thumbnail by calculating closest percentage
			$pw = MAX_IMAGE_DIM / $ow;
			$ph = MAX_IMAGE_DIM / $oh;
			if ($pw > $ph) {
				$nw = round($ow * $ph);
				$nh = round($oh * $ph);
			}
			else {
				$nw = round($ow * $pw);
				$nh = round($oh * $pw);
			}
			$thumb = imagecreatetruecolor($nw,$nh);
			imagecopyresampled($thumb,$orig,0,0,0,0,$nw,$nh,$ow,$oh);
			// Write thumb
			$file_path = substr_replace($file_path, '_thumb', strrpos($file_path, '.'), 0);
			$itype($thumb, $file_path);
			chmod($file_path, 0644);
			// Remove from memory
			imagedestroy($orig);
			imagedestroy($thumb);
		}
		else
			$error_code = 9;
	}
		
	echo <<<EOF
<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
EOF;
	echo 'window.parent.OnUploadCompleted(' . ($error_code > 0 ? '1' : '0') . ',"' . str_replace($_SERVER['DOCUMENT_ROOT'], '', $file_path) . '","' . $_FILES['NewFile']['name'] . '","' . file_upload_error_message($error_code) . '") ;' ;
	echo '</script>' ;
?>